<template>
  <div class="dialog_container">
    <!-- 图片选择裁剪弹框 -->
    <el-dialog
      v-model="visible"
      title="裁剪图片"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="25vh"
      center
      width="600px"
    >
      <div v-loading="dialogLoading" class="dialog_content">
        <vue-cropper
          ref="cropperRef"
          :src="imgSrc"
          :ready="cropImage"
          :zoom="cropImage"
          :cropmove="cropImage"
          style="width: 100%; height: 400px"
        ></vue-cropper>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button class="crop-demo-btn" type="primary" size="small">
            选择其它图片
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="image/*"
              @change="setImage"
            />
          </el-button>
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            上传并保存
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import VueCropper from "vue-cropperjs";
import "cropperjs/dist/cropper.css";
// import { getBase64Image } from "../utils/common";

export default {
  name: "CropperImageDialog",
  components: { VueCropper },
  setup(props, context) {
    // const { proxy } = getCurrentInstance();
    // const $api = proxy.$api;

    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);

    const cropperRef = ref(null);
    const imgSrc = ref("");
    const cropImg = ref("");

    /**
     * 上传并保存
     */
    const handleConfirm = () => {
      // 触发事件，把数据传递给父组件
      if (cropImg.value) {
        context.emit("croped", cropImg.value);
      } else {
        ElMessage.warning("抱歉，图片截取失败，请关闭弹窗重试");
      }
    };

    /**
     * 打开弹框
     */
    const open = (imgPath) => {
      console.log("打开弹框 ===> imgPath", imgPath);
      // getBase64Image(imgPath)
      //   .then((base64URL) => {
      //     imgSrc.value = base64URL;
      //   })
      //   .catch((err) => {
      //     console.error("getBase64Image error: ", err);
      //   });
      imgSrc.value = imgPath;
      visible.value = true;
    };

    /**
     * 关闭弹框
     */
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    /**
     * 重置数据
     */
    const resetData = () => {
      imgSrc.value = "";
    };

    /**
     * 裁剪图片
     */
    const cropImage = () => {
      cropImg.value = cropperRef.value.getCroppedCanvas().toDataURL();
    };

    /**
     * 选择图片
     */
    const setImage = (e) => {
      const file = e.target.files[0];
      const isJPG =
        file.type.toLowerCase() === "image/jpeg" ||
        file.type.toLowerCase() === "image/png";
      const isOverSize = file.size / 1024 / 1024 > 1;
      if (!isJPG) {
        return ElMessage.warning("请上传jpg/jpeg/png格式文件");
      }
      if (isOverSize) {
        return ElMessage.warning("选择图片大小不能超过1MB!");
      }
      const reader = new FileReader();
      reader.onload = (event) => {
        visible.value = true;
        imgSrc.value = event.target.result;
        cropperRef.value && cropperRef.value.replace(event.target.result);
      };
      reader.readAsDataURL(file);
    };

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      open,
      close,
      handleConfirm,
      cropperRef,
      cropImg,
      imgSrc,
      cropImage,
      setImage,
    };
  },
};
</script>

<style lang="less" scoped>
.dialog_container {
}
.dialog_content {
  height: 400px;
}
.dialog_footer {
  .crop-demo-btn {
    position: relative;
  }
  .crop-input {
    position: absolute;
    width: 104px;
    height: 32px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
  }
  .button {
    padding: 0;
    min-height: auto;
  }
  .clearfix {
    line-height: 28px;
  }
}
</style>
